<!--
 * @Description:
 * @version:
 * @Author: 娃哈哈
 * @Date: 2024-12-21 21:05:26
-->
<template>
  <div class="map-section">
    <div class="map" ref="map" id="map"> </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, inject, watch } from 'vue';
import MapInit from '@/utils/MapInit'; // 假设 MapInit 是一个模块
import areaJson from '@/utils/金凤区.json'
import { PopupType } from '../../index.d'
import { currentGET } from "@/api";

// 定义响应式变量
const latticePointInfoData = ref(null);
const lay = ref(null);
const lay1 = ref(null);
const openMap = ref(null);
const markers = ref([]); // 存储打点
const areaMapJson = ref(areaJson)
const polygons = ref([]); // 存储多边形覆盖物

// 初始化地图
// 初始化地图
const initMap = async () => {
  try {
    // 配置天地图 URL
    //const imageURLT = `/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=e9815b3f8d98c4c723b87f46ece4c284`;
    const imageURLT = `/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=e9815b3f8d98c4c723b87f46ece4c284`;
    //  const imageURLT1 = `http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=e9815b3f8d98c4c723b87f46ece4c284`
      const imageURLT2 = `/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=e9815b3f8d98c4c723b87f46ece4c284`
      // 创建图层
    // lay.value = new T.TileLayer(imageURLT, { minZoom: 6, maxZoom: 18, zIndex: 1 });
      lay1.value = new T.TileLayer(imageURLT2, { minZoom: 6, maxZoom: 18, zIndex: 2 });
      lay.value = new T.TileLayer(imageURLT, { minZoom: 6, maxZoom: 18, zIndex: 2 });

    // 创建地图实例
      const config = { layers: [lay1.value, lay.value] };
    openMap.value = new T.Map('map', config);

    // 设置地图中心和缩放级别
    openMap.value.centerAndZoom(new T.LngLat(105.889899,38.47107), 11.4); // 调整为所需的经纬度和缩放级别
  } catch (error) {
    console.error('Error initializing the map:', error);
  }
};
// 获取点信息
// const getLatticePointInfoData = async (type) => {
//   // 在这里实现你的获取点信息的逻辑
//   latticePointInfoData.value = `Data for type: ${type}`; // 示例逻辑
// };
// 加载数据
const loadData = async () => {
  // 示例数据，实际数据可以从 API 加载
  // const data = [
  //   { id: 1, name: 'Point A', lng: 106.1, lat: 38.53 },
  //   { id: 2, name: 'Point B', lng: 106.2, lat: 38.54 },
  //   { id: 3, name: 'Point C', lng: 106.3, lat: 38.55 },
  // ];
  currentGET("enterpriseList").then((res) => {
    console.log(res);
    if (res.success) {
        // 在地图上打点
        res.data.list.map(item => {
          return {
            id: item.id, 
            name: item.enterpriseName, 
            lng: item.lng, 
            lat: item.lat
          }
        }).forEach(point => {
          addMarker(point);
        });
    }
  });
};

// 监听父组件或祖先弹窗开启
const showPopup = inject('showPopup')
// 添加打点功能
const addMarker = (point) => {
  const marker = new T.Marker(new T.LngLat(point.lng, point.lat));
    marker.addEventListener('click', () => {
      showPopup({ type: 22, show: true, popupFlag: 'enterpriseView', searchInfo: {id: point.id }})
        // showPopup({ type: 3, show: true, popupFlag: 'mapPopup' })
        // alert(`Marker clicked: ${point.name}`);
  });
  openMap.value.addOverLay(marker);
  markers.value.push(marker);
};

// 清除所有打点
const clearMarkers = () => {
  markers.value.forEach(marker => {
    openMap.value.removeOverLay(marker);
  });
  markers.value = [];
};
// 绘制多边形覆盖物
const drawRears = (json, type) => {
  const colorObj = {
    countyAndDistrict: "lightgreen",
    plantingArea: "#0263f4",
  };

  json.features.forEach((feature, index) => {
    const points = feature.geometry.coordinates[0].map(coord => new T.LngLat(coord[0], coord[1]));
    const name = feature.properties.XIAN_NAME;

    const color = '#0263f4';
    const polygon = new T.Polygon(points, {
      color,
      weight: 3,
      opacity: 1,
      fillColor: color,
      fillOpacity: 0,
      dashArray: [5, 5],    // 设置虚线样式：[线段长度, 间隙长度]
      name,
    });

    polygon.addEventListener("click", (e) => {
      const labelName = e.target.options.name;
      const latlng = new T.LngLat(e.lnglat.lng, e.lnglat.lat);
      const label = new T.Label({
        text: labelName,
        position: latlng,
      });

      label.setBackgroundColor("#040E3E");
      label.setFontColor("#ffffff");
      label.setBorderColor("#00E0E7");
      label.setOffset(new T.Point(-20, -15));

      openMap.value.addOverLay(label);
      label.addEventListener("mouseout", () => {
        openMap.value.removeOverLay(label);
      });
    });

    openMap.value.addOverLay(polygon);
    polygons.value.push(polygon);
  });
};

// 生命周期
onMounted(async () => {
  await MapInit.init();
  await initMap();
  await loadData();
  await drawRears(areaMapJson.value, "areaMap"); // 使用传入的 JSON 数据
});
</script>

<style scoped>
.map-section {
  width: 100%;
  height: 100%;
}

.map {
  background: rgb(45, 61, 108,.3);
  width: 100%;
  height: 100%;
  z-index: 0;
}
</style>
